import type { App, Directive, DirectiveBinding } from 'vue'
import { useAuthStore } from '@/stores/auth'

/**
 * 权限指令
 * 用法：
 * 1. 单个权限：v-permission="'system:user:create'"
 * 2. 多个权限（满足一个即可）：v-permission="['system:user:create', 'system:user:edit']"
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const authStore = useAuthStore()
    const permissions = authStore.permissions

    if (value) {
      const hasPermission = checkPermission(value, permissions)
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    } else {
      throw new Error("需要指定权限值，例如：v-permission=\"'system:user:create'\"")
    }
  }
}

/**
 * 检查是否有权限
 * @param value 权限值，可以是字符串或字符串数组
 * @param permissions 用户拥有的权限列表
 * @returns 是否有权限
 */
function checkPermission(value: string | string[], permissions: string[]): boolean {
  if (!value) {
    return false
  }

  if (!permissions || permissions.length === 0) {
    return false
  }

  if (typeof value === 'string') {
    return permissions.includes(value)
  }

  if (Array.isArray(value)) {
    return value.some(item => permissions.includes(item))
  }

  return false
}

export function setupPermission(app: App) {
  app.directive('permission', permission)
} 